/**
 * 调用 XYZ.validate 返回validator对象.
 * 
 * validator的常用方法: 
 * validator.focusInvalid(); // 聚焦到第一个错误的element
 * validator.numberOfInvalids(); // 获取错误的提示信息
 * 
 * validate的常用方法
 * $form.valid(); // 校验表单, 无错误则返回true, 否则返回false
 * 
 * @description
 * 其他方法
 * $("#myinput").rules("add", {required: true, messages: {required: "Required input"}});
 * $("#myinput").rules("remove");
 * $("#myinput").rules("remove", "min max");
 * 
 * rule#remote
 * remote: {
 *	type:"POST",
 *	url:"verifyName",
 * 	data:{
 *		id: function() {return $("#id").val();},
 *		pid: function() {return zTreeObj.getSelectedNodes()[0].id;}
 *		}
 *	}
 * 
 * rule.required, true or false, or function, or expression (example '#myinput:checked' / :unchecked) return boolean value
 * document at http://jqueryvalidation.org/category/selectors/
 * 
 * 最新的validate文档
 * http://jqueryvalidation.org/validate/
 * @author
 * @example XYZ.validate($form, {validate原来的参数,一般情况只用写rules, messages, 回调函数	callback: {	focusout: null }});
 */

XYZ = window.XYZ || {};

XYZ.validate = function($form, options) {
	var defaultOptions = {
		debug: false,
		onkeyup: false,
		focusInvalid: true,
		// default: ':hidden'
		// Inputs of type submit and reset are always ignored, so are disabled elements.
		ignore: '.ignore',
		// Callback for custom code when an invalid form is submitted.
		invalidHandler: function(event, validator) {
		},
		// default validate elements (except checkboxes/radio buttons) on blur.
		onfocusout: function(element, event) {
			if (!this.checkable(element)) {
				// 对于非必填项清空内容后, 插件不会消除错误信息. 这是临时代码, 应该通过插件api来完成该功能
				var $element = $(element);
				if($.trim($element.val()).length == 0) {
					$element.siblings('.invalid-tips').remove();
				}
				
				this.element(element);
				event.stopPropagation();
			}
		},
		showErrors: function(errorMap, errorList) {
			// this.defaultShowErrors();
		},
		errorClass: 'invalid',
		validClass: 'valid',
		errorElement: 'label',
		success: function(label, element){
			// element is not jQuery object
			jQuery(element).parent().find('.invalid-tips').remove();
		},
		errorPlacement: function(error, element) {
			var parent = element.parent();
			var errMsg = error.html();
			if(parent.find('.invalid-tips').length == 0) {
				jQuery('<div class="invalid-tips"><i class="glyphicon glyphicon-exclamation-sign"></i>&nbsp;<span>' + errMsg + '</span></div>').appendTo(parent);
			} else {
				parent.find('.invalid-tips span').html(errMsg);
			}
		},
		// framework will return false or the return value;
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit();
		},
		rules: {
			
		},
		messages: {
			
		}
	};

	jQuery.extend(jQuery.validator.messages, {
		required: "必须填写",
		remote: "请修正此栏位",
		email: "请输入有效的电子邮件",
		url: "请输入有效的网址",
		date: "请输入有效的日期",
		dateISO: "请输入有效的日期 (YYYY-MM-DD)",
		number: "请输入正确的数字",
		digits: "只可输入数字",
		creditcard: "请输入有效的信用卡号码",
		equalTo: "你的输入不相同",
		extension: "请输入有效的后缀",
		maxlength: jQuery.validator.format("最多 {0} 个字"),
		minlength: jQuery.validator.format("最少 {0} 个字"),
		rangelength: jQuery.validator.format("请输入长度为 {0} 至 {1} 之间的字串"),
		range: jQuery.validator.format("请输入 {0} 至 {1} 之间的数值"),
		max: jQuery.validator.format("请输入不大于 {0} 的数值"),
		min: jQuery.validator.format("请输入不小于 {0} 的数值")
	});
	
	jQuery.validator.addMethod("regex", function(value, element, params) {
		return this.optional(element) || params.test(value);
	}, '正则匹配有误');
	
	var validator = $form.validate(jQuery.extend({}, defaultOptions, options));
	return validator;
};

if (typeof define === "function" && define.amd) {
	define("validate", [], function() {
		return XYZ.validate;
	});
}
